package com.yfp.tissue.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.uuid.Snowflake;
import com.yfp.common.datascope.annotation.DataScope;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.api.RemoteOperationService;
import com.yfp.operation.domain.Receiver;
import com.yfp.system.api.domain.SysUser;
import com.yfp.system.api.model.LoginUser;
import com.yfp.tissue.domain.Dto.RouteDTO;
import com.yfp.tissue.domain.entity.Area;
import com.yfp.tissue.domain.entity.Machine;
import com.yfp.tissue.domain.entity.Position;
import com.yfp.tissue.domain.entity.PositionSharing;
import com.yfp.tissue.domain.vo.PositionVO;
import com.yfp.tissue.mapper.*;
import com.yfp.tissue.mapper.*;
import com.yfp.tissue.service.AreaService;
import com.yfp.tissue.service.PositionService;
import com.yfp.tissue.service.PositionSharingService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: ydyfp
 * @DESCRIPTION:
 * @USER: xiaohuya
 * @DATE: 2023/12/19 13:08
 */

@Service
@Slf4j
public class PositionServiceImpl implements PositionService {
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private MachineMapper machineMapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysUserCompanyMapper sysUserCompanyMapper;
    @Resource
    private PositionSharingService positionSharingService;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private RemoteOperationService remoteOperationService;
    @Resource
    private AreaService areaService;

    @Override
    @Transactional
    public R addPosition(Position position) {
        log.info("新增点位入参:{}", position);

        List<Receiver> receivers = new ArrayList<>();
        Receiver receiver = null;
        Snowflake snowflake = new Snowflake(1);
        position.setPositionId(String.valueOf(snowflake.nextId()));
        String positionId = position.getPositionId();

        String areaId = position.getAreaId();
        Area area = areaService.getById(areaId);

        List<PositionSharing> positionSharings = position.getPositionSharings();
        if (CollUtil.isNotEmpty(positionSharings)) {
            List<Long> strings = new ArrayList<>();
            for (PositionSharing positionSharing : positionSharings) {
                // 根据userId和用户类型校验，如果同一个用户本次提交的类型跟分账表里的类型不一样，不让通过
                List<PositionSharing> list = positionSharingService.selectSharings(positionSharing);
                if (list != null && list.size() > 0) {
                    return R.fail("一个用户只能存在一种分账身份");
                } else {
                    Long userId = positionSharing.getUserId();
                    if (strings.contains(userId)) {
                        return R.fail("每个用户同一点位只能设置一个分账账号");
                    } else {
                        strings.add(userId);
                    }
                }
                positionSharing.setPositionId(positionId);
                receiver = new Receiver();
                BeanUtils.copyProperties(positionSharing, receiver);
                if (receiver.getUserId() != -1) {
                    SysUser sysUser = userMapper.selectUserById(receiver.getUserId());
                    receiver.setNickName(sysUser.getNickName());
                }
                receiver.setProceedsAccount(position.getProceedsAccount());
                receivers.add(receiver);
            }
            log.info("新增点位，插入投资人列表:{}", positionSharings);
            R<Void> addResult = remoteOperationService.addReceiver(receivers);
            if (addResult.getCode() != 200) {
                return R.fail(addResult.getMsg());
            }
            // 批量插入
            positionSharingService.insertAll(positionSharings);
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();

        position.setUpdateName(loginUser.getSysUser().getNickName());
        position.setCreateName(loginUser.getSysUser().getNickName());
        position.setEnable("1");
        position.setIsDelete(false);
        position.setDeptId(loginUser.getSysUser().getDeptId());
        position.setCityName(area.getCityName());
        positionMapper.insert(position);

        return R.ok();

    }

    @DataScope(deptAlias = "p")
    @Override
    public List<PositionVO> queryPosition(RouteDTO routeDTO) {
        List<PositionVO> positionVOS = positionMapper.queryPosition(routeDTO);
        this.geSharing(positionVOS);
        return positionVOS;
    }

    @Override
    public List<PositionVO> findList(RouteDTO routeDTO) {
        return positionMapper.findList(routeDTO);
    }

    /**
     * 获取投资人列表
     *
     * @param positionVOS
     */
    public void geSharing(List<PositionVO> positionVOS) {
        if (positionVOS != null && positionVOS.size() > 0) {
            List<String> positionIds = positionVOS.stream().map(positionVO -> positionVO.getPositionId()).collect(Collectors.toList());
            if (!positionIds.isEmpty()) {
                List<PositionSharing> list = positionSharingService.getByPositionIds(positionIds);
                for (PositionVO positionVO : positionVOS) {
                    String positionId = positionVO.getPositionId();
                    List<PositionSharing> sharingList = list.stream().filter(positionSharing -> positionSharing.getPositionId().equals(positionId)).collect(Collectors.toList());
                    positionVO.setPositionSharings(sharingList);
                }
            }
        }
    }

    @Override
    public R positionDetail(String positionId) {
        PositionVO positionVO = positionMapper.queryPositionDetail(positionId);
        Machine machine = new Machine();
        machine.setPositionId(positionId);
        List<Machine> machines = machineMapper.queryAllByLimit(machine);
        List<PositionSharing> positionSharings = positionSharingService.findByPositionId(positionId);
        positionVO.setPositionSharings(positionSharings);
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("positions", positionVO);
        hashMap.put("machines", machines);
        return R.ok(hashMap);
    }

    @Override
    @Transactional
    public R updatePosition(Position position) {
        log.info("修改点位");
        LoginUser loginUser = SecurityUtils.getLoginUser();

        List<Receiver> receivers = new ArrayList<>();
        Receiver receiver = null;

        String positionId = position.getPositionId();
        List<PositionSharing> positionSharings = position.getPositionSharings();

        if (positionSharings != null && positionSharings.size() > 0) {
            List<Long> strings = new ArrayList<>();
            for (PositionSharing positionSharing : positionSharings) {
                // 根据userId和用户类型校验，如果同一个用户本次提交的类型跟分账表里的类型不一样，不让通过
                List<PositionSharing> list = positionSharingService.selectSharings(positionSharing);
                if (list != null && list.size() > 0) {
                    return R.fail("一个用户只能存在一种分账身份");
                } else {
                    Long userId = positionSharing.getUserId();
                    if (strings.contains(userId)) {
                        return R.fail("每个用户同一点位只能设置一个分账账号");
                    } else {
                        strings.add(userId);
                    }
                }
                positionSharing.setPositionId(positionId);
                receiver = new Receiver();
                BeanUtils.copyProperties(positionSharing, receiver);
                if (receiver.getUserId() != -1) {
                    SysUser sysUser = userMapper.selectUserById(receiver.getUserId());
                    receiver.setNickName(sysUser.getNickName());
                }
                receiver.setProceedsAccount(position.getProceedsAccount());
                receivers.add(receiver);
            }
            log.info("修改点位，插入投资人列表:{}", positionSharings);
            R<Void> addResult = remoteOperationService.addReceiver(receivers);
            if (addResult.getCode() != 200) {
                return R.fail(addResult.getMsg());
            }
        }
        // 批量插入
        positionSharingService.delByPositionId(position.getPositionId());
        if (CollUtil.isNotEmpty(positionSharings)) {
            positionSharingService.insertAll(positionSharings);
        }
        position.setUpdateName(loginUser.getSysUser().getNickName());
        // 每次修改都会将点位状态改成禁用
        position.setEnable("0");

        // 客服人员信息修改
        // PositionVO positionVO = positionMapper.queryPositionDetail(positionId);
        // if (Objects.nonNull(positionVO) && Objects.nonNull(positionVO.getOperationUserId()) && !NumberUtil.equals(positionVO.getOperationUserId(), position.getOperationUserId())) {
        //     // 删除客服人信息
        //     Machine machine = new Machine();
        //     machine.setPositionId(positionId);
        //     List<Machine> machines = machineMapper.queryAllByLimit(machine);
        //     List<String> machineIds = machines.stream().map(Machine::getMachineId).collect(Collectors.toList());
        //     if (CollUtil.isNotEmpty(machineIds)) {
        //         R<Void> voidR = remoteOperationService.delOperationUser(positionVO.getOperationUserId(), machineIds);
        //         if (R.isError(voidR)) {
        //             return R.fail(voidR.getMsg());
        //         }
        //     }
        // }

        String areaId = position.getAreaId();
        Area area = areaService.getById(areaId);
        position.setCityName(area.getCityName());
        positionMapper.update(position);
        return R.ok();
    }

    /**
     * 根据点位id获取投资人列表
     *
     * @param positionId
     * @return
     */
    @Override
    public R<List<PositionSharing>> getPositionSharings(String positionId) {
        List<PositionSharing> list = positionSharingService.getPositionSharings(positionId);
        return R.ok(list);
    }

    /**
     * 获取点位id列表
     *
     * @return
     */
    @Override
    @DataScope(deptAlias = "p")
    public List<Position> getPositionIds(Position position) {
        return positionMapper.getPositionIds(position);
    }

    @Override
    public Position getInfoByMachineId(String machineId) {
        List<Position> positions = positionMapper.getInfoByMachineId(machineId);
        return CollUtil.getFirst(positions);
    }

    @Override
    public List<Position> findByAreaId(String areaId) {
        return positionMapper.findByAreaId(areaId);
    }

    @Override
    public List<Position> findPositionDraw(String areaId, String positionId) {
        return positionMapper.findPositionDraw(areaId, positionId);
    }
}
